package com.zty.framework.web.service;

import com.zty.common.utils.DateUtils;
import com.zty.system.domain.*;
import com.zty.system.mapper.ParentMapper;
import com.zty.system.mapper.StudentMapper;
import com.zty.system.mapper.SysUserPostMapper;
import com.zty.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.zty.common.constant.CacheConstants;
import com.zty.common.constant.Constants;
import com.zty.common.constant.UserConstants;
import com.zty.common.core.domain.entity.SysUser;
import com.zty.common.core.domain.model.RegisterBody;
import com.zty.common.core.redis.RedisCache;
import com.zty.common.exception.user.CaptchaException;
import com.zty.common.exception.user.CaptchaExpireException;
import com.zty.common.utils.MessageUtils;
import com.zty.common.utils.SecurityUtils;
import com.zty.common.utils.StringUtils;
import com.zty.framework.manager.AsyncManager;
import com.zty.framework.manager.factory.AsyncFactory;
import com.zty.system.service.ISysConfigService;
import com.zty.system.service.ISysUserService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 注册校验方法
 * 
 * @author zty
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ParentMapper parentMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setDeptId(registerBody.getDeptId());
            sysUser.setSex(registerBody.getSex());
            sysUser.setAvatar(registerBody.getAvatar());
            if (StringUtils.isNotNull(registerBody.getEmail())){
                sysUser.setEmail(registerBody.getEmail());
            }
            if (StringUtils.isNotNull(registerBody.getPhonenumber())){
                sysUser.setPhonenumber(registerBody.getPhonenumber());
            }
            boolean regFlag = userService.registerUser(sysUser);
            Long userId = userService.selectUserByUserName(username).getUserId();
            insertUserPost(userId,registerBody.getPostIds());
            boolean isParentRegister = registerBody.getParentRegister();
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                if (!isParentRegister){ //学生
                    SysStudent sysStudent = new SysStudent();
                    sysStudent.setUserId(userId);
                    sysStudent.setLocation(registerBody.getLocation());
                    sysStudent.setMajor(registerBody.getMajor());
                    sysStudent.setUniversity(registerBody.getUniversity());
                    sysStudent.setTeachWay(registerBody.getTeachWay());
                    sysStudent.setBackground(registerBody.getBackground());
                    sysStudent.setCreateBy(username);
                    sysStudent.setCreateTime(DateUtils.getNowDate());
                    sysStudent.setAuthStatus("0");
                    sysStudent.setSalaryExpect(registerBody.getSalaryExpect());
                    studentMapper.batchSysStudent(sysStudent);
                    userRoleMapper.batchUserRole(Collections.singletonList(new SysUserRole(userId,3L)));
                }else { //学员
                    SysParent sysParent = new SysParent();
                    sysParent.setUserId(userId);
                    sysParent.setLocation(registerBody.getLocation());
                    sysParent.setBackground(registerBody.getBackground());
                    sysParent.setSalaryReward(registerBody.getSalaryExpect());
                    sysParent.setCreateBy(username);
                    sysParent.setCreateTime(DateUtils.getNowDate());
                    sysParent.setAuthStatus("0");
                    parentMapper.batchSysParent(sysParent);
                    userRoleMapper.batchUserRole(Collections.singletonList(new SysUserRole(userId,4L)));
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 新增用户岗位信息
     */
    public void insertUserPost(Long userId,List<Long> postIds)
    {
        if (StringUtils.isNotEmpty(postIds))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(postIds.size());
            for (Long postId : postIds)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(userId);
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
